<template>
  <div class="">
    <div class="app-box">
      <div class="attrTitle">基本信息</div>
      <a-divider></a-divider>
      <div class="main-box">
        <a-form-model ref="mainForm" :model="hteFile" :rules="mainRule">
          <a-row :gutter="24">
            <a-col v-if="hteFile.projectNo" :span="12">
              <a-form-model-item v-bind="formItemLayout" label="文件名称" tyle="width: 100%" prop="fileName">
                <a-textarea v-model="hteFile.fileName" :auto-size="true" />
              </a-form-model-item>
            </a-col>
            <a-col v-else :span="24">
              <a-form-model-item
                v-bind="{
                  labelCol: {
                    xs: { span: 24 },
                    md: { span: 4 },
                  },

                  wrapperCol: {
                    xs: { span: 24 },
                    md: { span: 18 },
                  },
                }"
                label="文件名称"
                tyle="width: 100%"
                prop="fileName"
              >
                <a-textarea v-model="hteFile.fileName" :auto-size="true" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12" v-if="hteFile.projectNo">
              <a-form-model-item v-bind="formItemLayout" label="项目编号" tyle="width: 100%">
                <a-input v-model.trim="hteFile.projectNo" disabled />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="文件类别" tyle="width: 100%" prop="fileType">
                <a-tree-select
                  v-model="hteFile.fileType"
                  :tree-data="treeData"
                  placeholder="请选择文件类别"
                  tree-default-expand-all
                  @change="handleFileType"
                >
                </a-tree-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="文件编号" tyle="width: 100%">
                <a-input v-model.trim="hteFile.fileNo" placeholder="不填写将会自动生成" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24" v-if="parentId != 2">
              <a-form-model-item
                v-bind="{
                  labelCol: {
                    xs: { span: 24 },
                    md: { span: 4 },
                  },

                  wrapperCol: {
                    xs: { span: 24 },
                    md: { span: 18 },
                  },
                }"
                label="关键词"
                tyle="width: 100%"
                prop="keywords"
              >
                <a-textarea v-model="hteFile.keywords" :auto-size="true" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="parentId != 2">
              <a-form-model-item
                v-bind="{
                  labelCol: {
                    xs: { span: 24 },
                    md: { span: 4 },
                  },

                  wrapperCol: {
                    xs: { span: 24 },
                    md: { span: 18 },
                  },
                }"
                label="文件中文摘要"
                tyle="width: 100%"
                prop="purpose"
              >
                <a-textarea v-model="hteFile.purpose" :auto-size="true" placeholder="" />
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="版本号" tyle="width: 100%">
                <a-input v-model="hteFile.version" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="创建人" tyle="width: 100%">
                <a-input v-model="hteFile.createUser" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="发布人" tyle="width: 100%">
                <a-input v-model="hteFile.publishUser" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="发布部门" tyle="width: 100%">
                <a-input v-model="hteFile.publishDept" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="发布生效时间" tyle="width: 100%">
                <a-input v-model="hteFile.effectTime" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item v-bind="formItemLayout" label="创建部门" tyle="width: 100%">
                <a-input v-model="hteFile.addDept" disabled placeholder="自动生成" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                prop="purpose"
                :labelCol="{ md: 4, xs: 24 }"
                :wrapperCol="{ md: 18, xs: 24 }"
                label="文件用途"
                style="width: 100%"
              >
                <a-textarea v-model="hteFile.purpose" />
              </a-form-model-item>
            </a-col>
          </a-row> -->
        </a-form-model>
      </div>
      <div class="attrTitle" v-show="classAttrList.length > 0" style="margin-top: 10px">
        关键信息
        <span v-if="parentId == 2 && !!hteFile.id" style="color: #f5222d; font-size: 12px"
          >(保存后;修改业务板块;文件编号不会重新生成)</span
        >
      </div>
      <a-divider></a-divider>
      <libFileAttr
        v-if="parentId == 2"
        ref="fileattr"
        :classAttrList="classAttrList"
        :formItemLayout="formItemLayout"
        :parentId="parentId"
        :hteFile="hteFile"
      ></libFileAttr>
      <FileAttrNormal
        v-if="parentId == 4"
        ref="fileattr"
        :classAttrList="classAttrList"
        :formItemLayout="formItemLayout"
        :parentId="parentId"
        :hteFile="hteFile"
      ></FileAttrNormal>
      <!-- <a-form :form="form">
        <div class="attr-box" v-show="classAttrList.length > 0">
          <a-form-item
            v-bind="formItemLayout"
            class="attr-item"
            v-for="(item, key) in classAttrList"
            :key="key"
            :label="item.name"
          >
            <a-input
              v-if="item.required"
              v-decorator="[
                'value' + item.attrId,
                { rules: [{ required: true, message: '请输入' + item.name }], initialValue: item.content },
              ]"
            />
            <a-input v-else v-model="item.content" />
          </a-form-item>
        </div>
      </a-form> -->
    </div>
  </div>
</template>

<script>
import { getAction, getActionAsync } from '@/api/manage'
import LibFileAttr from '@/views/library/components/LibFileAttr'
import FileAttrNormal from '@/views/library/components/FileAttrNormal'
export default {
  components: { LibFileAttr, FileAttrNormal },

  props: {
    parentId: {
      type: String,
      default: null,
    },
    projectNo: {
      type: String,
      default: null,
    },
    hteFile: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      let len = this.getByteLength(value)
      if (len > 1000) {
        cb(new Error('文件中文摘要不能超过500个字符'))
      } else {
        return cb()
      }
    }
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 18 },
          sm: { span: 8 },
        },

        wrapperCol: {
          xs: { span: 20 },
          sm: { span: 12 },
        },
      },
      labelColRow: {
        xs: { span: 21 },
        sm: { span: 3 },
      },
      treeData: [],
      classAttrList: [],
      urls: {
        getTreeList: '/lib/hteFileClass/getTreeList',
        listAttr: '/lib/hteLibFile/attrs',
      },
      form: this.$form.createForm(this, { name: 'form' }),
      mainRule: {
        fileName: [{ required: true, message: '请输入文件名称', trigger: 'change' }],
        fileType: [{ required: true, message: '请输入文件分类', trigger: 'change' }],
        fileType: [{ required: true, message: '请输入文件分类', trigger: 'change' }],
        // fileNo: [{ required: true, message: '请输入文件编号', trigger: 'change' }],
        // issuedDate: [{ required: true, message: '请选择实施日期', trigger: 'change' }],
        // purpose: [{ required: true, message: '请输入文件用途', trigger: 'change' }],
        keywords: [{ required: true, message: '请输入关键词', trigger: 'change' }],
        purpose: [
          { required: true, message: '请输入文件中文摘要', trigger: 'change' },
          { validator: checkEmail, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.fetchClassTree()
    //this.handleFileType();
  },
  mounted() {},
  methods: {
    /**
     * 获取分类树
     */
    fetchClassTree() {
      getAction(this.urls.getTreeList, { parentId: this.parentId }).then((res) => {
        if (res.success) {
          if (this.parentId == 2) {
            this.selectableTreeData(res.result.treeList)
          }
          this.treeData = res.result.treeList
        } else {
          this.$message.error('获取分类树错误')
        }
      })
    },
    selectableTreeData(data) {
      data.forEach((it, i) => {
        it.selectable = false
        if (!it.children || it.children.length == 0) {
          it.selectable = true
        } else {
          this.selectableTreeData(it.children)
        }
      })
    },
    /**
     * 获取分类扩展属性
     */
    async fetchClassAttr(classId, fileId = 0, version = 0) {
      if (this.hteFile.fileType) {
        let classId = this.hteFile.fileType
        let classAttrRes = await getActionAsync(
          this.urls.listAttr + '?classId=' + classId + '&fileId=' + 0 + '&version=' + 0,
          {}
        )
        let classAttr = classAttrRes.result

        getAction(this.urls.listAttr + '?classId=' + classId + '&fileId=' + fileId + '&version=' + version, {}).then(
          (res) => {
            if (res.success) {
              let oldAttr = res.result
              classAttr.forEach((item, i) => {
                var check = oldAttr.find((attr) => {
                  return attr.name == item.name
                })
                if (!!check) {
                  classAttr[i] = check
                }
              })

              this.classAttrList = classAttr
            } else {
              this.$message.error('获取分类拓展属性错误')
            }
          }
        )
      } else {
        this.classAttrList = []
      }
    },
    checkHteFile() {
      let flag = false
      this.$refs.mainForm.validate((vaild) => {
        if (vaild) {
          flag = true
        }
      })
      return flag
    },
    getHteFile() {
      //文件编码前缀
      let prefix = this.$refs.fileattr.businessPrefix

      this.hteFile.prefix = prefix
      return this.hteFile
    },
    setHteFile(hteFile) {
      this.hteFile = hteFile
      this.handleFileType()
    },
    checkClassAttr() {
      // let flag = false
      // this.form.validateFields((err, values) => {
      //   if (!err) {
      //     flag = true
      //   }
      // })

      // return flag
      let flag = this.$refs.fileattr.checkClassAttr()

      return flag
    },
    getClassAttr() {
      // this.form.validateFields((err, values) => {
      //   if (!err) {
      //     const checkParams = { ...values }
      //     this.classAttrList.forEach((attr) => {
      //       if (attr.required) {
      //         attr.content = checkParams['value' + attr.attrId]
      //       }
      //     })
      //   }
      // })

      // return this.classAttrList

      return this.$refs.fileattr.getClassAttr()
    },
    handleFileType(value) {
      this.fetchClassAttr(this.hteFile.fileType, this.hteFile.id, this.hteFile.draftVersion)
      this.checkFileType()
    },
    checkFileType() {
      let currentFileType = this.getFileType(this.treeData)

      while (
        currentFileType &&
        ['学位论文', '电子期刊'].indexOf(currentFileType.title) < 0 &&
        currentFileType.parentId
      ) {
        currentFileType = this.getParentFileType(this.treeData, currentFileType.parentId)
      }

      if (currentFileType && ['学位论文', '电子期刊'].indexOf(currentFileType.title) > -1) {
        return this.$set(this.hteFile, 'projectNo', this.projectNo)
      } else {
        this.$set(this.hteFile, 'projectNo', '')
      }
    },
    getFileType(list) {
      for (let l of list) {
        if (l.value == this.hteFile.fileType) {
          return l
        } else {
          if (l.children && l.children.length > 0) {
            let cl = this.getFileType(l.children)
            if(cl){
              return cl
            }
          }
        }
      }
    },
    getParentFileType(list, parentId) {
      for (let l of list) {
        if (l.value == parentId) {
          return l
        } else {
          if (l.children && l.children.length > 0) {
            let cl =  this.getParentFileType(l.children, parentId)
            if(cl){
              return cl
            }
          }
        }
      }
    },
    getByteLength(str = '') {
      let len = 0
      for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
          len += 2
        } else {
          len++
        }
      }
      return len
    },
  },
  watch: {
    // 'hteFile.fileType': {
    //   handler: function (newVal, oldVal) {
    //       if (newVal && newVal != 0) {
    //         this.fetchClassAttr(this.hteFile.fileType, this.hteFile.id, this.hteFile.draftVersion)
    //       }
    //   },
    //   deep:true
    // },
  },
}
</script>

<style scoped>
.app-container {
  margin-top: 5px;
  height: auto;
}
.attr-box {
  width: 100%;
  /* display: flex;
  align-content: flex-start;
  flex-flow: row wrap; */
}

/* .attr-item {
  width: 50%;
  margin-bottom: 20px;
} */
.attrTitle {
  height: 40px;
  line-height: 40px;
  text-align: left;
  font-size: 20px;
  font-weight: bold;
  color: #000;
}
.ant-form-item {
  margin-bottom: 5px !important;
}
</style>
